<template>
  <div class="app-container">
    <!-- 顶部工具栏 -->
    <div class="filter-container">
      <!-- 第一行: 网站选择 + 搜索过滤 -->
      <div style="margin-bottom: 10px;">
        <el-select
          v-model="currentWebsiteId"
          placeholder="选择网站"
          size="mini"
          style="width: 300px;"
          class="filter-item"
          filterable
          @change="handleWebsiteChange"
        >
          <el-option
            v-for="site in websites"
            :key="site.id"
            :label="site.name + ' (' + site.domain + ')'"
            :value="site.id"
          />
        </el-select>
        <el-input
          v-model="listQuery.kw"
          placeholder="搜索页面标题..."
          size="mini"
          style="width: 200px;"
          class="filter-item"
          clearable
          @keyup.enter.native="handleFilter"
          @clear="handleFilterAndSave"
        />

        <el-select
          v-model="listQuery.tasks"
          placeholder="包含任务（已完成）"
          size="mini"
          style="width: 200px;"
          class="filter-item"
          multiple
          collapse-tags
          clearable
          @change="handleIncludeTasksChange"
        >
          <el-option label="📄 MD配置已创建" value="md_config_created" />
          <el-option label="✏️ AI源码完成" value="ai_code_completed" />
          <el-option label="🖼️ 图片优化完毕" value="images_optimized" />
          <el-option label="🔍 SEO优化完毕" value="seo_optimized" />
          <el-option label="✅ 内容优化完毕" value="content_optimized" />
        </el-select>
        <el-button
          v-if="listQuery.tasks.length > 0"
          size="mini"
          type="text"
          icon="el-icon-close"
          style="margin-left: -5px; color: #909399;"
          @click="clearIncludeTasks"
        >
          清空
        </el-button>

        <el-select
          v-model="listQuery.exclude_tasks"
          placeholder="排除任务（已完成）"
          size="mini"
          style="width: 200px;"
          class="filter-item"
          multiple
          collapse-tags
          clearable
          @change="handleExcludeTasksChange"
        >
          <el-option
            v-for="task in availableExcludeTasks"
            :key="task.value"
            :label="task.label"
            :value="task.value"
            :disabled="task.disabled"
          />
        </el-select>
        <el-button
          v-if="listQuery.exclude_tasks.length > 0"
          size="mini"
          type="text"
          icon="el-icon-close"
          style="margin-left: -5px; color: #909399;"
          @click="clearExcludeTasks"
        >
          清空
        </el-button>

        <el-select
          v-model="listQuery.status"
          placeholder="状态"
          size="mini"
          style="width: 150px;"
          class="filter-item"
          clearable
          @change="handleFilterAndSave"
        >
          <el-option label="草稿" value="draft" />
          <el-option label="MD已创建" value="md_created" />
          <el-option label="代码生成中" value="ai_generating" />
          <el-option label="已发布" value="published" />
        </el-select>

        <el-select
          v-model="listQuery.page_type"
          placeholder="页面类型"
          size="mini"
          style="width: 150px;"
          class="filter-item"
          clearable
          @change="handleFilterAndSave"
        >
          <el-option label="落地页" value="landing" />
          <el-option label="信息聚合页" value="info_aggregation" />
          <el-option label="产品页面" value="product" />
          <el-option label="产品目录页" value="product_catalog" />
          <el-option label="目录落地页" value="catalog_landing" />
          <el-option label="博客文章页" value="blog_article" />
        </el-select>

        <el-button
          class="filter-item"
          size="mini"
          type="primary"
          icon="el-icon-search"
          @click="handleFilter"
        >
          搜索
        </el-button>
      </div>

      <!-- 第二行: 操作按钮 -->
      <div>
        <!-- Git状态标签 -->
        <template v-if="currentWebsiteDomain">
          <template v-if="gitStatusLoading">
            <el-tag
              size="mini"
              class="filter-item"
              style="margin-right: 10px;"
            >
              <i class="el-icon-loading" /> 加载中...
            </el-tag>
          </template>
          <template v-else-if="gitStatus.is_git_repo">
            <el-tag
              v-if="gitStatus.needs_pull"
              type="danger"
              size="mini"
              class="filter-item"
              style="margin-right: 10px;"
            >
              <i class="el-icon-download" /> 需要拉取 ({{ gitStatus.behind_count }} 个新提交)
            </el-tag>
            <el-tag
              v-else-if="gitStatus.has_changes"
              type="warning"
              size="mini"
              class="filter-item"
              style="margin-right: 10px;"
            >
              <i class="el-icon-warning" /> 有未提交的变更
            </el-tag>
            <el-tag
              v-else
              type="success"
              size="mini"
              class="filter-item"
              style="margin-right: 10px;"
            >
              <i class="el-icon-check" /> 工作区干净
            </el-tag>
          </template>
        </template>

        <!-- Git操作按钮 -->
        <template v-if="gitStatus.is_git_repo && currentWebsiteId">
          <el-dropdown
            trigger="click"
            class="filter-item"
            style="margin-right: 10px;"
            @command="handleGitCommand"
          >
            <el-button size="mini" icon="el-icon-s-operation">
              Git操作 <i class="el-icon-arrow-down el-icon--right" />
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="refresh" icon="el-icon-refresh">
                刷新状态
              </el-dropdown-item>
              <el-dropdown-item command="pull" icon="el-icon-download" divided>
                拉取更新
              </el-dropdown-item>
              <el-dropdown-item command="commit" icon="el-icon-upload">
                提交并推送
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>

        <!-- 同步到生产环境开关(仅本地环境显示) -->
        <el-checkbox
          v-if="canSyncToProduction"
          v-model="syncToProduction"
          class="filter-item"
          size="mini"
          style="margin-right: 10px; font-size: 12px;"
          @change="handleSyncSettingChange"
        >
          <i class="el-icon-refresh" style="margin-right: 3px;" />
          同步到生产
        </el-checkbox>

        <el-button
          class="filter-item"
          size="mini"
          type="success"
          icon="el-icon-plus"
          @click="handleCreate"
        >
          新建页面
        </el-button>
        <el-button
          class="filter-item"
          size="mini"
          type="warning"
          icon="el-icon-document-copy"
          @click="handleAIBatch"
        >
          AI批量创建
        </el-button>
      </div>

      <!-- 批量操作按钮 -->
      <el-button
        v-if="canSyncToProduction && multipleSelection.length > 0"
        class="filter-item"
        size="mini"
        type="primary"
        icon="el-icon-upload2"
        :loading="batchSyncing"
        @click="handleBatchSyncToProduction"
      >
        批量同步到生产环境 ({{ multipleSelection.length }})
      </el-button>
    </div>

    <!-- 页面列表 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="handleSortChange"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
      />

      <el-table-column label="ID" width="80" align="center">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>

      <el-table-column label="页面标题" min-width="200">
        <template slot-scope="{row}">
          <el-link type="primary" @click="handlePreview(row)">
            <strong>{{ row.title }}</strong>
          </el-link>
          <div style="font-size: 12px; color: #999;">{{ row.slug }}</div>
          <div v-if="row.operation_note" style="font-size: 12px; color: #E6A23C; margin-top: 3px; display: flex; align-items: center; gap: 5px;">
            <i class="el-icon-warning" />
            <span style="flex: 1;">{{ row.operation_note }}</span>
            <el-button
              type="text"
              icon="el-icon-edit"
              size="mini"
              style="padding: 0; color: #409EFF;"
              @click.stop="showEditOperationNoteDialog(row)"
            />
          </div>
          <div v-else style="margin-top: 3px;">
            <i
              class="el-icon-chat-line-square"
              style="font-size: 14px; color: #999; cursor: pointer;"
              @click.stop="showEditOperationNoteDialog(row)"
            />
          </div>
          <el-tag v-if="row.is_home" size="mini" type="warning" style="margin-top: 3px;">首页</el-tag>
          <el-tag v-if="row.ai_generated" size="mini" type="success" style="margin-top: 3px;">AI</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="优先级" width="150" align="center" sortable="custom" prop="priority">
        <template slot-scope="{row}">
          <el-rate
            v-model="row.priority"
            :max="5"
            show-text
            :texts="['最低', '低', '中', '高', '最高']"
            @change="handlePriorityChange(row)"
          />
        </template>
      </el-table-column>

      <el-table-column label="任务进度" width="200" align="center">
        <template slot-scope="{row}">
          <div style="display: flex; flex-direction: column; align-items: center; gap: 5px;">
            <div style="display: flex; gap: 3px; font-size: 18px;">
              <!-- MD配置 - 文档图标 -->
              <i
                class="el-icon-document"
                :style="{color: row.md_config_created ? '#67C23A' : '#DCDFE6', cursor: 'pointer'}"
                :title="'MD配置' + (row.md_config_created ? '已创建' : '未创建')"
                @click="toggleTask(row, 'md_config_created')"
              />
              <!-- AI源码 - 代码图标 -->
              <i
                class="el-icon-edit"
                :style="{color: row.ai_code_completed ? '#67C23A' : '#DCDFE6', cursor: 'pointer'}"
                :title="'AI源码' + (row.ai_code_completed ? '完成' : '未完成')"
                @click="toggleTask(row, 'ai_code_completed')"
              />
              <!-- 图片优化 - 图片图标 -->
              <i
                class="el-icon-picture"
                :style="{color: row.images_optimized ? '#67C23A' : '#DCDFE6', cursor: 'pointer'}"
                :title="'图片' + (row.images_optimized ? '已优化' : '未优化')"
                @click="toggleTask(row, 'images_optimized')"
              />
              <!-- SEO优化 - 搜索图标 -->
              <i
                class="el-icon-search"
                :style="{color: row.seo_optimized ? '#67C23A' : '#DCDFE6', cursor: 'pointer'}"
                :title="'SEO' + (row.seo_optimized ? '已优化' : '未优化')"
                @click="toggleTask(row, 'seo_optimized')"
              />
              <!-- 内容优化 - 检查图标 -->
              <i
                class="el-icon-finished"
                :style="{color: row.content_optimized ? '#67C23A' : '#DCDFE6', cursor: 'pointer'}"
                :title="'内容' + (row.content_optimized ? '已优化' : '未优化')"
                @click="toggleTask(row, 'content_optimized')"
              />
            </div>
            <el-progress
              :percentage="getTaskCompletionPercentage(row)"
              :color="getTaskCompletionColor(row)"
              :format="() => getTaskCompletionText(row)"
              style="width: 100%;"
            />
          </div>
        </template>
      </el-table-column>

      <el-table-column label="类型" width="120" align="center">
        <template slot-scope="{row}">
          <el-select
            v-model="row.page_type"
            size="small"
            @change="handlePageTypeChange(row)"
          >
            <el-option label="落地页" value="landing" />
            <el-option label="信息聚合页" value="info_aggregation" />
            <el-option label="产品页" value="product" />
            <el-option label="产品目录页" value="product_catalog" />
            <el-option label="目录落地页" value="catalog_landing" />
            <el-option label="博客文章页" value="blog_article" />
          </el-select>
        </template>
      </el-table-column>

      <el-table-column label="状态" width="200" align="center">
        <template slot-scope="{row}">
          <div style="display: flex; align-items: center; justify-content: center; gap: 5px;">
            <el-select
              v-model="row.status"
              size="small"
              style="flex: 1;"
              @change="handleStatusChange(row)"
            >
              <el-option label="草稿" value="draft" />
              <el-option label="AI生成中" value="ai_generating" />
              <el-option label="MD已创建" value="md_created" />
              <el-option label="AI源码完成" value="source_code_generated" />
              <el-option label="图片优化完毕" value="images_optimized" />
              <el-option label="SEO优化完毕" value="seo_optimized" />
              <el-option label="内容优化完毕" value="manual_optimized" />
              <el-option label="可发布" value="ready_to_publish" />
              <el-option label="待审核" value="review" />
              <el-option label="已发布" value="published" />
              <el-option label="已归档" value="archived" />
            </el-select>
            <el-tooltip
              v-if="canSyncToProduction"
              content="同步状态到生产环境"
              placement="top"
            >
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-upload2"
                circle
                :loading="row.syncing"
                @click="handleSyncStatusToProduction(row)"
              />
            </el-tooltip>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="来源" width="130" align="center">
        <template slot-scope="{row}">
          <el-select
            v-model="row.content_source"
            size="small"
            @change="handleContentSourceChangeInList(row)"
          >
            <el-option label="手动创建" value="manual" />
            <el-option label="AI生成" value="ai_generated" />
            <el-option label="博客文章" value="post" />
          </el-select>
        </template>
      </el-table-column>

      <el-table-column label="部署方式" width="150" align="center">
        <template slot-scope="{row}">
          <el-select
            v-if="row.content_source === 'post'"
            v-model="row.deployment_method"
            size="small"
            @change="handleDeploymentMethodChange(row)"
          >
            <el-option label="直接替换" value="replace" />
            <el-option label="AI生成" value="ai_generate" />
            <el-option label="创建MD" value="create_md" />
          </el-select>
          <span v-else style="color: #999; font-size: 12px;">-</span>
        </template>
      </el-table-column>

      <el-table-column label="更新时间" width="160" align="center">
        <template slot-scope="{row}">
          <span>{{ row.update_at | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="580" align="center" fixed="right">
        <template slot-scope="{row}">
          <!-- 常用操作 -->
          <el-button type="primary" size="mini" icon="el-icon-edit" @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button
            size="mini"
            icon="el-icon-document"
            type="success"
            @click="handleBuildMD(row)"
          >
            构建MD
          </el-button>
          <el-button
            size="mini"
            icon="el-icon-s-tools"
            type="success"
            @click="openGrapesJSEditor(row)"
          >
            可视化编辑
          </el-button>
          <el-button
            size="mini"
            icon="el-icon-view"
            type="info"
            @click="handlePreview(row)"
          >
            预览
          </el-button>

          <!-- 更多操作下拉菜单 -->
          <el-dropdown style="margin-left: 5px;" @command="(command) => handleMoreAction(command, row)">
            <el-button size="mini">
              更多<i class="el-icon-arrow-down el-icon--right" />
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="quickEdit" icon="el-icon-setting">
                编辑设置
              </el-dropdown-item>
              <el-dropdown-item command="generateCode" icon="el-icon-magic-stick">
                创建源码
              </el-dropdown-item>
              <el-dropdown-item command="syncImages" icon="el-icon-picture">
                同步图片
              </el-dropdown-item>
              <el-dropdown-item
                v-if="row.status === 'draft'"
                command="publish"
                icon="el-icon-upload"
                divided
              >
                发布
              </el-dropdown-item>
              <el-dropdown-item command="delete" icon="el-icon-delete" divided>
                删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-if="total>0"
      background
      class="mt-pagination"
      :current-page="listQuery.page"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="listQuery.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handlePageChange"
    />

    <!-- 创建/编辑页面对话框 -->
    <el-dialog
      :title="dialogStatus === 'create' ? '新建页面' : '编辑页面'"
      :visible.sync="dialogFormVisible"
      width="90%"
      top="5vh"
    >
      <el-form
        ref="dataForm"
        :model="temp"
        :rules="rules"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="页面标题" prop="title">
              <el-input v-model="temp.title" placeholder="请输入页面标题" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="URL路径" prop="slug">
              <el-input v-model="temp.slug" placeholder="about-us" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="页面类型">
              <el-select v-model="temp.page_type" placeholder="选择页面类型">
                <el-option label="落地页" value="landing" />
                <el-option label="信息聚合页面（例如FAQ，解决方案等）" value="info_aggregation" />
                <el-option label="产品页面" value="product" />
                <el-option label="产品目录页" value="product_catalog" />
                <el-option label="目录落地页" value="catalog_landing" />
                <el-option label="博客文章页面" value="blog_article" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-select v-model="temp.status">
                <el-option label="草稿" value="draft" />
                <el-option label="已发布" value="published" />
                <el-option label="已归档" value="archived" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 博客相关配置 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="内容来源">
              <el-select v-model="temp.content_source" placeholder="选择内容来源" @change="handleContentSourceChange">
                <el-option label="手动创建" value="manual" />
                <el-option label="AI生成" value="ai_generated" />
                <el-option label="博客文章" value="post" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="temp.content_source === 'post'" label="关联文章">
              <el-select
                v-model="temp.related_post"
                placeholder="选择博客文章"
                filterable
                remote
                :remote-method="searchPosts"
                :loading="postLoading"
              >
                <el-option
                  v-for="post in postList"
                  :key="post.id"
                  :label="post.title"
                  :value="post.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-if="temp.content_source === 'post'" :gutter="20">
          <el-col :span="12">
            <el-form-item label="部署方式">
              <el-select v-model="temp.deployment_method" placeholder="选择部署方式">
                <el-option label="直接替换" value="replace">
                  <span>直接替换</span>
                  <span style="float: right; color: #8492a6; font-size: 12px;">使用模板占位符替换</span>
                </el-option>
                <el-option label="AI生成" value="ai_generate">
                  <span>AI生成</span>
                  <span style="float: right; color: #8492a6; font-size: 12px;">AI重新生成完整页面</span>
                </el-option>
                <el-option label="创建Markdown" value="create_md">
                  <span>创建Markdown</span>
                  <span style="float: right; color: #8492a6; font-size: 12px;">生成MD文件供SSG使用</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="temp.deployment_method === 'replace'" label="博客模板">
              <el-select
                v-model="temp.template_id"
                placeholder="选择博客模板"
                filterable
                clearable
              >
                <el-option
                  v-for="tpl in templateList"
                  :key="tpl.id"
                  :label="tpl.name"
                  :value="tpl.id"
                >
                  <span>{{ tpl.name }}</span>
                  <span v-if="tpl.description" style="float: right; color: #8492a6; font-size: 12px;">
                    {{ tpl.description.substring(0, 20) }}{{ tpl.description.length > 20 ? '...' : '' }}
                  </span>
                </el-option>
              </el-select>
              <div style="font-size: 12px; color: #999; margin-top: 5px;">
                使用"直接替换"方式时需要选择包含final_html的模板
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="SEO标题">
              <el-input v-model="temp.meta_title" placeholder="留空则使用页面标题" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="SEO关键词">
              <el-input v-model="temp.meta_keywords" placeholder="关键词1, 关键词2" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="SEO描述">
          <el-input
            v-model="temp.meta_description"
            type="textarea"
            :rows="2"
            placeholder="页面简短描述，用于搜索引擎..."
          />
        </el-form-item>

        <!-- 页面生成Prompt -->
        <el-form-item label="页面生成Prompt">
          <el-input
            v-model="temp.page_prompt"
            type="textarea"
            :rows="5"
            placeholder="详细描述这个页面的生成要求，包括内容、风格、目标受众等..."
          />
          <div style="font-size: 12px; color: #999; margin-top: 5px;">
            此Prompt用于生成配置文件(.md)和AI创建页面
          </div>
        </el-form-item>

        <el-form-item label="HTML内容">
          <el-input
            v-model="temp.html_content"
            type="textarea"
            :rows="15"
            placeholder="页面HTML代码..."
            style="font-family: monospace;"
          />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="CSS代码">
              <el-input
                v-model="temp.css_content"
                type="textarea"
                :rows="8"
                placeholder="自定义CSS样式..."
                style="font-family: monospace;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="JavaScript代码">
              <el-input
                v-model="temp.js_content"
                type="textarea"
                :rows="8"
                placeholder="自定义JavaScript代码..."
                style="font-family: monospace;"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="设为首页">
          <el-switch v-model="temp.is_home" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">
          保存
        </el-button>
      </div>
    </el-dialog>

    <!-- AI批量创建Drawer -->
    <el-drawer
      title="AI批量创建页面"
      :visible.sync="aiBatchVisible"
      direction="rtl"
      size="90%"
      :before-close="handleBatchDrawerClose"
    >
      <div class="batch-drawer-content">
        <!-- 两列布局 -->
        <el-row :gutter="20" style="height: 100%;">
          <!-- 左侧：AI对话 -->
          <el-col :span="12" style="height: 100%;">
            <AIInnerChat
              ref="batchPageGenerator"
              api-url="/static_web/api/ai/chat/"
              handler-name="batch_page_generator"
              :context-data="batchContext"
              :suggested-questions="batchSuggestedQuestions"
              placeholder="输入您的回答或选择上面的快捷操作..."
              :auto-parse-json="false"
              :show-fill-button="false"
              @message-completed="handleAIMessage"
            />
          </el-col>

          <!-- 右侧：页面预览 -->
          <el-col :span="12" style="height: 100%;">
            <div class="batch-preview-panel">
              <div class="panel-header">
                <span class="panel-title">
                  <i class="el-icon-document" /> 即将创建的页面
                  <span v-if="parsedPages.length > 0" class="page-count">({{ parsedPages.length }}个)</span>
                </span>
              </div>

              <!-- 页面列表预览 -->
              <div v-if="parsedPages.length > 0" class="pages-preview-list">
                <el-card
                  v-for="(page, index) in parsedPages"
                  :key="index"
                  class="page-preview-item"
                  shadow="hover"
                >
                  <div class="page-item-header">
                    <span class="page-number">{{ index + 1 }}</span>
                    <h4>{{ page.title }}</h4>
                  </div>
                  <div class="page-item-details">
                    <p><strong>URL:</strong> {{ page.slug }}.html</p>
                    <p v-if="page.page_type || page.language">
                      <strong>配置:</strong>
                      <span v-if="page.page_type">{{ getPageTypeLabel(page.page_type) }}</span>
                      <span v-if="page.page_type && page.language"> | </span>
                      <span v-if="page.language">{{ getLanguageLabel(page.language) }}</span>
                    </p>
                    <p v-if="page.ai_prompt" class="page-desc">
                      <strong>AI提示:</strong><br>
                      {{ page.ai_prompt }}
                    </p>
                  </div>
                </el-card>
              </div>

              <!-- 空状态 -->
              <div v-else class="empty-preview">
                <i class="el-icon-chat-dot-round" style="font-size: 48px; color: #DCDFE6;" />
                <p>与AI对话收集页面信息后，这里会显示页面预览</p>
              </div>
            </div>
          </el-col>
        </el-row>

        <!-- 底部操作按钮 -->
        <div class="drawer-footer">
          <el-button @click="aiBatchVisible = false">取消</el-button>
          <el-button
            type="primary"
            icon="el-icon-plus"
            style="background-color: #1EB7E6; border-color: #1EB7E6;"
            :loading="batchCreating"
            :disabled="parsedPages.length === 0"
            @click="confirmBatchCreate"
          >
            确认创建 {{ parsedPages.length }} 个页面
          </el-button>
        </div>
      </div>
    </el-drawer>

    <!-- 编辑操作备注对话框 -->
    <el-dialog
      title="编辑操作备注"
      :visible.sync="operationNoteDialogVisible"
      width="600px"
    >
      <el-input
        v-model="currentOperationNote"
        type="textarea"
        :rows="6"
        placeholder="请输入操作备注，用于记录页面当前状态、待办事项等协作信息..."
        maxlength="500"
        show-word-limit
      />
      <div slot="footer">
        <el-button @click="operationNoteDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="savingNote" @click="savePageOperationNote">保存</el-button>
      </div>
    </el-dialog>

    <!-- AI操作对话框 (AITask组件) -->
    <AITask ref="aiTaskDialog" @success="handleAISuccess" />

    <!-- AI源码生成助手 -->
    <AIEmbedChat
      ref="sourceCodeGenerator"
      :visible.sync="sourceCodeVisible"
      title="AI源码生成助手"
      api-url="/static_web/api/ai/chat/"
      handler-name="source_code_generator"
      :context-data="sourceCodeContext"
      :left-span="12"
      :right-span="12"
      placeholder="输入指令（例如：开始编写代码 / 继续写 / 添加响应式支持）"
    >
      <!-- 右侧：源代码显示区 -->
      <template #right-panel="{ messages }">
        <div class="source-code-panel">
          <div class="panel-header">
            <span class="panel-title">
              <i class="el-icon-document" /> 生成的源代码
              <span class="code-stats">{{ extractedCodeLines }} 行</span>
            </span>
            <div class="panel-actions">
              <el-button
                size="mini"
                icon="el-icon-document-copy"
                @click="copyExtractedCode"
              >
                复制
              </el-button>
              <el-button
                type="success"
                size="mini"
                icon="el-icon-download"
                :loading="savingCode"
                :disabled="!extractedCode"
                @click="saveExtractedCode"
              >
                保存到文件
              </el-button>
            </div>
          </div>
          <el-input
            v-model="extractedCode"
            type="textarea"
            :rows="30"
            placeholder="AI生成的代码将在这里显示..."
            class="code-editor"
            readonly
          />
        </div>
      </template>

      <!-- 底部按钮 -->
      <template #footer="{ close }">
        <el-button @click="close">关闭</el-button>
        <el-button
          type="success"
          icon="el-icon-download"
          :loading="savingCode"
          :disabled="!extractedCode"
          @click="saveExtractedCode"
        >
          保存源代码
        </el-button>
      </template>
    </AIEmbedChat>

  </div>
</template>

<script>
import { Get as GetWebsites } from '@/api/static_web/website'
import { Get, Post, Put, Delete, Publish, BuildMD, CheckFiles } from '@/api/static_web/page'
import { syncPageImages } from '@/api/static_web_cloud_image'
import AITask from '@/components/AITask'
import AIEmbedChat from '@/components/AIEmbedChat'
import AIInnerChat from '@/components/AIInnerChat'
import request from '@/utils/request'
import Cookies from 'js-cookie'

export default {
  name: 'StaticWebPages',
  components: { AITask, AIEmbedChat, AIInnerChat },
  data() {
    return {
      websites: [],
      currentWebsiteId: null,
      currentWebsiteDomain: '',
      gitStatusLoading: false,
      gitStatus: {
        is_git_repo: false,
        has_changes: false,
        needs_pull: false,
        behind_count: 0,
        ahead_count: 0,
        current_branch: '',
        remote_url: ''
      },
      // 所有可用的任务选项
      allTaskOptions: [
        { label: '📄 MD配置已创建', value: 'md_config_created' },
        { label: '✏️ AI源码完成', value: 'ai_code_completed' },
        { label: '🖼️ 图片优化完毕', value: 'images_optimized' },
        { label: '🔍 SEO优化完毕', value: 'seo_optimized' },
        { label: '✅ 内容优化完毕', value: 'content_optimized' }
      ],
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        pagesize: 20,
        kw: '',
        status: '',
        page_type: '',
        tasks: [], // 包含任务（已完成的任务）
        exclude_tasks: [], // 排除任务（已完成的任务）
        sort: '-update_at' // 默认按更新时间倒序
      },
      temp: {
        id: undefined,
        website_id: null,
        title: '',
        slug: '',
        page_type: 'landing',
        meta_title: '',
        meta_description: '',
        meta_keywords: '',
        html_content: '',
        css_content: '',
        js_content: '',
        status: 'draft',
        is_home: false,
        page_prompt: '', // 页面生成Prompt
        content_source: 'manual', // 内容来源
        related_post: null, // 关联的博客文章ID
        deployment_method: 'replace', // 部署方式
        template_id: null // 模板ID
      },
      postList: [], // 博客文章列表
      postLoading: false, // 文章搜索加载状态
      templateList: [], // 模板列表
      dialogFormVisible: false,
      dialogStatus: '',
      rules: {
        title: [{ required: true, message: '请输入页面标题', trigger: 'blur' }],
        slug: [{ required: true, message: '请输入URL路径', trigger: 'blur' }]
      },
      aiBatchVisible: false,
      batchContext: {},
      parsedPages: [],
      batchCreating: false,
      batchSuggestedQuestions: [
        {
          title: '创建产品页面',
          question: '我要创建多个产品页面，标题如下（逗号分隔）：Custom Flags, Feather Flags, Teardrop Flags, Banner Flags',
          icon: 'el-icon-goods',
          color: '#1EB7E6'
        },
        {
          title: '快速开始',
          question: '开始创建页面',
          icon: 'el-icon-magic-stick',
          color: '#67C23A'
        },
        {
          title: '多行输入',
          question: '我有一个标题列表（每行一个）：\n产品A\n产品B\n产品C',
          icon: 'el-icon-document-add',
          color: '#E6A23C'
        },
        {
          title: '查看帮助',
          question: '如何批量创建页面？有什么格式要求吗？',
          icon: 'el-icon-question',
          color: '#909399'
        }
      ],
      currentEditPage: null,
      currentPageId: null,
      currentPageTitle: '',
      sourceCodeVisible: false,
      sourceCodeContext: {},
      extractedCode: '',
      savingCode: false,
      canSyncToProduction: false,
      productionProjectId: 14, // 默认生产环境项目ID
      operationNoteDialogVisible: false,
      currentOperationNote: '',
      currentEditingPage: null,
      savingNote: false,
      multipleSelection: [], // 批量选择的页面
      batchSyncing: false, // 批量同步状态
      syncToProduction: true // 同步到生产环境开关,默认开启
    }
  },
  computed: {
    extractedCodeLines() {
      return this.extractedCode ? this.extractedCode.split('\n').length : 0
    },
    // 可用的排除任务选项（排除已被包含的任务）
    availableExcludeTasks() {
      return this.allTaskOptions.map(task => ({
        ...task,
        disabled: this.listQuery.tasks.includes(task.value)
      }))
    }
  },
  watch: {
    'sourceCodeVisible'(val) {
      if (val) {
        // 监听AI消息，自动提取代码
        this.$nextTick(() => {
          this.$watch(
            () => this.$refs.sourceCodeGenerator?.chatMessages,
            (messages) => {
              this.extractCodeFromMessages(messages)
            },
            { deep: true }
          )
        })
      }
    },
    'aiBatchVisible'(val) {
      if (!val) {
        // 关闭时清空数据
        this.parsedPages = []
        // 清空对话历史
        this.$nextTick(() => {
          if (this.$refs.batchPageGenerator) {
            this.$refs.batchPageGenerator.clearMessages()
          }
        })
      }
    }
  },
  created() {
    this.checkSyncAvailable()
    // 从路由参数获取website_id
    if (this.$route.query.website_id) {
      this.currentWebsiteId = parseInt(this.$route.query.website_id)
    }
    // 从 Cookie 恢复筛选条件
    this.loadFilterFromCookies()
    // 加载网站列表(会自动触发Git状态加载)
    this.loadWebsites()
  },
  methods: {
    loadWebsites() {
      GetWebsites().then(response => {
        this.websites = response.data.data

        // 如果URL中没有指定website_id，则自动选择
        if (!this.$route.query.website_id && this.websites.length > 0) {
          // 优先从Cookie读取上次选择
          const lastWebsiteId = Cookies.get('static_web_last_website_id')
          if (lastWebsiteId && this.websites.find(w => w.id === parseInt(lastWebsiteId))) {
            this.currentWebsiteId = parseInt(lastWebsiteId)
          } else {
            // 否则选择第一个
            this.currentWebsiteId = this.websites[0].id
          }
        }

        // 如果已经有选中的网站,初始化domain和Git状态
        if (this.currentWebsiteId) {
          const currentWebsite = this.websites.find(w => w.id === this.currentWebsiteId)
          if (currentWebsite) {
            this.currentWebsiteDomain = currentWebsite.domain
            this.loadGitStatus()
          }
          // 加载页面列表
          this.getList()
        }
      })
    },
    handleWebsiteChange() {
      // 保存选择到Cookie（7天有效期）
      if (this.currentWebsiteId) {
        Cookies.set('static_web_last_website_id', this.currentWebsiteId, { expires: 7 })
      }

      // 更新当前网站域名
      const currentWebsite = this.websites.find(w => w.id === this.currentWebsiteId)
      this.currentWebsiteDomain = currentWebsite ? currentWebsite.domain : ''

      // 加载Git状态
      if (this.currentWebsiteDomain) {
        this.loadGitStatus()
      }

      this.listQuery.page = 1
      this.getList()
    },
    getList() {
      if (!this.currentWebsiteId) {
        return
      }
      this.listLoading = true
      // 构建任务参数 - 多选任务用逗号分隔
      const tasksParam = this.listQuery.tasks && this.listQuery.tasks.length > 0
        ? this.listQuery.tasks.join(',')
        : ''
      const excludeTasksParam = this.listQuery.exclude_tasks && this.listQuery.exclude_tasks.length > 0
        ? this.listQuery.exclude_tasks.join(',')
        : ''
      const params = `page=${this.listQuery.page}&pagesize=${this.listQuery.pagesize}&kw=${this.listQuery.kw}&website_id=${this.currentWebsiteId}&status=${this.listQuery.status}&page_type=${this.listQuery.page_type}&tasks=${tasksParam}&exclude_tasks=${excludeTasksParam}&sort=${this.listQuery.sort}`
      Get(null, params).then(response => {
        this.list = response.data.data
        this.total = response.data.total
        this.listLoading = false
      }).catch(() => {
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      // 保存筛选条件到 Cookie
      this.saveFilterToCookies()
      this.getList()
    },
    handleFilterAndSave() {
      // 用于 select 组件的 @change 事件
      this.handleFilter()
    },
    // 处理包含任务变化
    handleIncludeTasksChange() {
      // 当选择包含任务时，自动将其他任务添加到排除任务
      const allTaskValues = this.allTaskOptions.map(t => t.value)
      const remainingTasks = allTaskValues.filter(t => !this.listQuery.tasks.includes(t))
      this.listQuery.exclude_tasks = remainingTasks
      this.handleFilter()
    },
    // 处理排除任务变化
    handleExcludeTasksChange() {
      // 移除被禁用的任务（即已在包含任务中的）
      this.listQuery.exclude_tasks = this.listQuery.exclude_tasks.filter(
        task => !this.listQuery.tasks.includes(task)
      )
      this.handleFilter()
    },
    // 清空包含任务
    clearIncludeTasks() {
      this.listQuery.tasks = []
      this.listQuery.exclude_tasks = []
      this.handleFilter()
    },
    // 清空排除任务
    clearExcludeTasks() {
      this.listQuery.exclude_tasks = []
      this.handleFilter()
    },
    handleSizeChange(val) {
      this.listQuery.pagesize = val
      this.getList()
    },
    handlePageChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        website_id: this.currentWebsiteId,
        title: '',
        slug: '',
        page_type: 'landing',
        meta_title: '',
        meta_description: '',
        meta_keywords: '',
        html_content: '',
        css_content: '',
        js_content: '',
        status: 'draft',
        is_home: false,
        page_prompt: '' // 页面生成Prompt
      }
    },
    handleCreate() {
      if (!this.currentWebsiteId) {
        this.$message.error('请先选择网站')
        return
      }
      // 跳转到新的页面编辑器
      this.$router.push({
        path: '/static_web/page-editor',
        query: { website_id: this.currentWebsiteId }
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // 博客类型验证
          if (this.temp.content_source === 'post') {
            if (!this.temp.related_post) {
              this.$message.warning('博客类型页面必须关联文章')
              return
            }
            if (this.temp.deployment_method === 'replace' && !this.temp.template_id) {
              this.$message.warning('使用直接替换方式时必须选择模板')
              return
            }
          }

          // 设置 website_id
          this.temp.website_id = this.currentWebsiteId

          Post(this.temp).then(() => {
            this.dialogFormVisible = false
            this.$message.success('创建成功')
            this.getList()
          }).catch(error => {
            this.$message.error('创建失败: ' + (error.message || '未知错误'))
          })
        }
      })
    },
    handleEdit(row) {
      // 跳转到新的页面编辑器
      this.$router.push({
        path: `/static_web/page-editor/${row.id}`,
        query: { website_id: this.currentWebsiteId }
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // 博客类型验证
          if (this.temp.content_source === 'post') {
            if (!this.temp.related_post) {
              this.$message.warning('博客类型页面必须关联文章')
              return
            }
            if (this.temp.deployment_method === 'replace' && !this.temp.template_id) {
              this.$message.warning('使用直接替换方式时必须选择模板')
              return
            }
          }

          Put(this.temp.id, this.temp).then(() => {
            this.dialogFormVisible = false
            this.$message.success('更新成功')
            this.getList()
          }).catch(error => {
            this.$message.error('更新失败: ' + (error.message || '未知错误'))
          })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('确定删除该页面吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        Delete(row.id).then(() => {
          this.$message.success('删除成功')
          this.getList()
        })
      })
    },
    // 处理下拉菜单操作
    handleMoreAction(command, row) {
      switch (command) {
        case 'quickEdit':
          this.handleQuickEdit(row)
          break
        case 'preview':
          this.handlePreview(row)
          break
        case 'generateCode':
          this.handleGenerateSourceCode(row)
          break
        case 'syncImages':
          this.handleSyncImages(row)
          break
        case 'visualEdit':
          this.openGrapesJSEditor(row)
          break
        case 'publish':
          this.handlePublish(row)
          break
        case 'delete':
          this.handleDelete(row)
          break
      }
    },
    // 快速编辑页面设置
    handleQuickEdit(row) {
      // 加载完整的页面数据
      Get(row.id).then(response => {
        if (response.success && response.data) {
          // 复制数据到 temp
          this.temp = Object.assign({}, response.data)

          // 如果是博客类型，加载文章列表和模板列表
          if (this.temp.content_source === 'post') {
            this.searchPosts('')
            this.loadTemplates()

            // 如果已经关联了文章，确保它在列表中
            if (this.temp.related_post) {
              // 获取文章详情并添加到列表
              import('@/api/cms/post').then(module => {
                const { Get } = module
                Get(this.temp.related_post).then(postResponse => {
                  if (postResponse.success && postResponse.data) {
                    // 检查是否已在列表中
                    const exists = this.postList.find(p => p.id === postResponse.data.id)
                    if (!exists) {
                      this.postList.unshift(postResponse.data)
                    }
                  }
                })
              })
            }
          }

          // 设置对话框状态
          this.dialogStatus = 'update'
          this.dialogFormVisible = true

          this.$nextTick(() => {
            this.$refs['dataForm'].clearValidate()
          })
        }
      }).catch(error => {
        this.$message.error('加载页面数据失败: ' + error.message)
      })
    },
    handlePublish(row) {
      Publish(row.id).then(() => {
        this.$message.success('发布成功')
        this.getList()
      })
    },
    handleBuildMD(row) {
      if (!row.page_prompt) {
        this.$message.warning('该页面还没有生成 Prompt，请先通过页面编辑器与 AI 对话生成 Prompt')
        return
      }

      this.$confirm('将为此页面生成 .md 配置文件到静态网站目录', '确认生成', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '正在生成 .md 文件...',
          spinner: 'el-icon-loading'
        })

        BuildMD(row.id).then(response => {
          loading.close()
          const data = response.data
          const messages = [
            `✅ MD 文件生成成功：${data.md_filename}`,
            `📁 图片目录：${data.image_dir}`,
            `🖼️ 生成了 ${data.image_prompts_count} 个图片 Prompt 文件`
          ]

          this.$notify({
            title: '构建成功',
            message: messages.join('<br/>'),
            dangerouslyUseHTMLString: true,
            type: 'success',
            duration: 8000
          })

          // 刷新列表，显示后端自动更新的任务状态（md_config_created）
          this.getList()

          // 如果生成了图片prompts，显示详细信息
          if (data.image_prompts_count > 0) {
            const imageList = data.image_prompts.map(img =>
              `• ${img.filename} → <strong>${img.target_image}</strong> (${img.description})`
            ).join('<br/>')

            this.$notify({
              title: '图片 Prompt 列表',
              message: imageList,
              dangerouslyUseHTMLString: true,
              type: 'info',
              duration: 10000,
              offset: 100
            })
          }
        }).catch(() => {
          loading.close()
          this.$message.error('生成失败')
        })
      }).catch(() => {
        // 用户取消
      })
    },
    handleSyncImages(row) {
      // 检查页面状态
      if (!['source_code_generated', 'manual_optimized', 'ready_to_publish', 'published'].includes(row.status)) {
        this.$message.warning('页面还没有生成源码，无法同步图片')
        return
      }

      this.$confirm(`确定要同步「${row.title}」页面中的图片吗？系统会扫描 HTML 文件中的所有云端图片链接并保存到数据库。`, '同步图片', {
        confirmButtonText: '开始同步',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '正在扫描页面并同步图片...',
          spinner: 'el-icon-loading'
        })

        syncPageImages({ page_id: row.id }).then(response => {
          loading.close()
          if (response.success) {
            const data = response.data
            this.$notify({
              title: '同步完成',
              message: `
                共发现 ${data.total_found} 个图片
                新保存 ${data.new_saved} 个
                已存在 ${data.already_exists} 个
                跳过 ${data.skipped} 个
                ${data.errors && data.errors.length > 0 ? `\n失败 ${data.errors.length} 个` : ''}
              `,
              type: 'success',
              duration: 8000
            })

            // 刷新列表，显示后端自动更新的任务状态（images_optimized）
            this.getList()

            if (data.errors && data.errors.length > 0) {
              console.error('同步失败的图片:', data.errors)
            }
          } else {
            this.$message.error(response.msg || '同步失败')
          }
        }).catch(error => {
          loading.close()
          this.$message.error('同步失败: ' + (error.message || '未知错误'))
          console.error('同步图片错误:', error)
        })
      }).catch(() => {
        // 用户取消
      })
    },
    handlePreview(row) {
      // 先检查文件状态
      CheckFiles(row.id).then(response => {
        const fileStatus = response.data

        // 检查文件后刷新列表，以显示后端自动更新的任务状态
        this.getList()

        if (fileStatus.html_exists) {
          // HTML文件存在，在新窗口打开预览
          const previewUrl = `${process.env.VUE_APP_BASE_API}${fileStatus.html_url}`
          window.open(previewUrl, '_blank')
        } else if (fileStatus.md_exists) {
          // MD存在但HTML不存在
          this.$confirm('HTML 文件不存在，但 MD 配置文件已生成。需要使用 Claude Code 读取 MD 文件创建 HTML 页面吗？', '提示', {
            confirmButtonText: '使用 Claude Code 创建',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.$message.info('请使用 Claude Code 读取 MD 文件并生成 HTML 页面')
            // TODO: 这里可以添加调用 Claude Code 的逻辑
          })
        } else if (fileStatus.has_prompt) {
          // 有Prompt但没有MD文件
          this.$confirm('页面还未构建 MD 配置文件。是否现在构建？', '提示', {
            confirmButtonText: '构建 MD',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.handleBuildMD(row)
          })
        } else {
          // 什么都没有
          this.$alert('该页面还没有生成 Prompt，请先通过页面编辑器与 AI 对话生成 Prompt', '无法预览', {
            confirmButtonText: '前往编辑',
            callback: () => {
              this.handleEdit(row)
            }
          })
        }
      }).catch(() => {
        this.$message.error('检查文件状态失败')
      })
    },
    // AI功能
    getPageTypeColor(type) {
      const colors = {
        'home': 'danger',
        'about': 'warning',
        'product': 'success',
        'blog': 'primary',
        'contact': 'info',
        'custom': ''
      }
      return colors[type] || ''
    },
    getPageTypeText(type) {
      const texts = {
        'home': '首页',
        'about': '关于',
        'product': '产品',
        'blog': '博客',
        'contact': '联系',
        'custom': '自定义'
      }
      return texts[type] || type
    },
    handleStatusChange(row) {
      // 快速更新状态
      Put(row.id, { status: row.status }).then(() => {
        this.$message.success('状态已更新')

        // 如果开启了同步到生产环境,自动同步
        if (this.syncToProduction && this.canSyncToProduction) {
          this.syncFieldToProduction(row.id, 'status', row.status, '页面状态')
        }
      }).catch(error => {
        console.error('更新状态失败:', error)
        this.$message.error('状态更新失败')
        // 失败时刷新列表恢复原状态
        this.getList()
      })
    },
    handlePageTypeChange(row) {
      // 快速更新页面类型
      Put(row.id, { page_type: row.page_type }).then(() => {
        this.$message.success('页面类型已更新')

        // 如果开启了同步到生产环境,自动同步
        if (this.syncToProduction && this.canSyncToProduction) {
          this.syncFieldToProduction(row.id, 'page_type', row.page_type, '页面类型')
        }
      }).catch(error => {
        console.error('更新页面类型失败:', error)
        this.$message.error('页面类型更新失败')
        this.getList()
      })
    },
    handlePriorityChange(row) {
      // 快速更新优先级
      Put(row.id, { priority: row.priority }).then(() => {
        this.$message.success('优先级已更新')

        // 如果开启了同步到生产环境,自动同步
        if (this.syncToProduction && this.canSyncToProduction) {
          this.syncFieldToProduction(row.id, 'priority', row.priority, '优先级')
        }
      }).catch(error => {
        console.error('更新优先级失败:', error)
        this.$message.error('优先级更新失败')
        this.getList()
      })
    },
    handleSortChange({ column, prop, order }) {
      // 处理排序变化
      if (prop === 'priority') {
        // 根据排序方向设置sort参数
        if (order === 'ascending') {
          this.listQuery.sort = 'priority' // 升序
        } else if (order === 'descending') {
          this.listQuery.sort = '-priority' // 降序
        } else {
          this.listQuery.sort = '-update_at' // 默认排序
        }
        this.listQuery.page = 1
        this.getList()
      }
    },
    // 计算任务完成百分比
    getTaskCompletionPercentage(row) {
      const tasks = [
        row.md_config_created,
        row.ai_code_completed,
        row.images_optimized,
        row.seo_optimized,
        row.content_optimized
      ]
      const completedCount = tasks.filter(t => t).length
      return Math.round((completedCount / tasks.length) * 100)
    },
    // 获取任务完成进度文本
    getTaskCompletionText(row) {
      const tasks = [
        row.md_config_created,
        row.ai_code_completed,
        row.images_optimized,
        row.seo_optimized,
        row.content_optimized
      ]
      const completedCount = tasks.filter(t => t).length
      return `${completedCount}/5`
    },
    // 获取任务完成进度颜色
    getTaskCompletionColor(row) {
      const percentage = this.getTaskCompletionPercentage(row)
      if (percentage === 100) return '#67C23A' // 绿色
      if (percentage >= 60) return '#E6A23C' // 橙色
      return '#F56C6C' // 红色
    },
    // 切换任务状态
    toggleTask(row, taskName) {
      const newValue = !row[taskName]
      const taskLabels = {
        md_config_created: 'MD配置',
        ai_code_completed: 'AI源码',
        images_optimized: '图片优化',
        seo_optimized: 'SEO优化',
        content_optimized: '内容优化'
      }

      // 更新本地数据
      row[taskName] = newValue

      // 调用API更新
      const updateData = {}
      updateData[taskName] = newValue

      Put(row.id, updateData).then(() => {
        this.$message.success(`${taskLabels[taskName]}已${newValue ? '完成' : '取消'}`)

        // 如果开启了同步到生产环境,自动同步
        if (this.syncToProduction && this.canSyncToProduction) {
          this.syncFieldToProduction(row.id, taskName, newValue, taskLabels[taskName])
        }
      }).catch(error => {
        console.error('更新任务状态失败:', error)
        this.$message.error('更新失败')
        // 恢复原状态
        row[taskName] = !newValue
      })
    },
    handleContentSourceChangeInList(row) {
      // 快速更新内容来源
      const updateData = { content_source: row.content_source }

      // 如果不是博客类型，清空相关字段
      if (row.content_source !== 'post') {
        updateData.related_post = null
        updateData.deployment_method = null
        updateData.template_id = null
        row.deployment_method = null
        row.related_post = null
        row.template_id = null
      } else {
        // 切换到博客类型时，设置默认部署方式
        if (!row.deployment_method) {
          updateData.deployment_method = 'replace'
          row.deployment_method = 'replace'
        }
      }

      Put(row.id, updateData).then(() => {
        this.$message.success('内容来源已更新')
      }).catch(error => {
        console.error('更新内容来源失败:', error)
        this.$message.error('内容来源更新失败')
        this.getList()
      })
    },
    handleDeploymentMethodChange(row) {
      // 快速更新部署方式
      Put(row.id, { deployment_method: row.deployment_method }).then(() => {
        this.$message.success('部署方式已更新')
      }).catch(error => {
        console.error('更新部署方式失败:', error)
        this.$message.error('部署方式更新失败')
        this.getList()
      })
    },
    getStatusType(status) {
      const types = {
        'draft': 'info',
        'ai_generating': 'warning',
        'md_created': 'primary',
        'source_code_generated': 'primary',
        'manual_optimized': 'success',
        'images_optimized': 'success',
        'ready_to_publish': 'success',
        'review': 'warning',
        'published': 'success',
        'archived': 'info'
      }
      return types[status] || ''
    },
    getStatusText(status) {
      const texts = {
        'draft': '草稿',
        'ai_generating': 'AI生成中',
        'md_created': 'MD已创建',
        'source_code_generated': 'AI源码完成',
        'images_optimized': '图片优化完毕',
        'manual_optimized': '内容优化完毕',
        'ready_to_publish': '可发布',
        'review': '待审核',
        'published': '已发布',
        'archived': '已归档'
      }
      return texts[status] || status
    },
    // 打开编辑源码页面
    openMediaAssets(row) {
      // 跳转到全屏源码编辑页面
      this.$router.push({
        path: `/media-assets/${row.id}`
      })
    },
    // 打开 GrapeJS 可视化编辑器
    openGrapesJSEditor(row) {
      // 在新窗口打开 GrapeJS 编辑器页面
      const routeData = this.$router.resolve({
        path: `/grapesjs-editor/${row.id}`
      })
      window.open(routeData.href, '_blank')
    },
    // 打开AI源码生成助手
    handleGenerateSourceCode(row) {
      // 检查是否已构建MD文件
      CheckFiles(row.id).then(response => {
        const fileStatus = response.data
        if (!fileStatus.md_exists) {
          this.$confirm('页面还未构建 MD 配置文件。是否现在构建？', '提示', {
            confirmButtonText: '构建 MD',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.handleBuildMD(row)
            this.$message.info('MD文件构建完成后，请再次点击"创建源码"按钮')
          })
          return
        }

        // 设置上下文数据
        this.currentPageId = row.id
        this.currentPageTitle = row.title
        this.sourceCodeContext = {
          page_id: row.id,
          current_code: this.extractedCode // 传入已有代码支持续写
        }

        // 清空之前的代码（如果需要重新生成）
        // this.extractedCode = ''

        // 打开对话框
        this.sourceCodeVisible = true
      }).catch(() => {
        this.$message.error('检查文件状态失败')
      })
    },

    // 从AI消息中提取代码
    extractCodeFromMessages(messages) {
      if (!messages || messages.length === 0) return

      let allCode = ''

      // 遍历所有assistant消息
      messages.forEach(msg => {
        if (msg.role === 'assistant' && msg.content) {
          // 提取```html代码块
          const htmlBlocks = msg.content.match(/```html\n([\s\S]*?)\n```/g)
          if (htmlBlocks) {
            htmlBlocks.forEach(block => {
              const code = block.replace(/```html\n/, '').replace(/\n```$/, '')
              allCode += code + '\n'
            })
          } else {
            // 尝试提取任意代码块
            const anyBlocks = msg.content.match(/```\n([\s\S]*?)\n```/g)
            if (anyBlocks) {
              anyBlocks.forEach(block => {
                const code = block.replace(/```\n/, '').replace(/\n```$/, '')
                allCode += code + '\n'
              })
            }
          }
        }
      })

      if (allCode) {
        this.extractedCode = allCode.trim()
        // 更新上下文中的当前代码，支持续写
        this.sourceCodeContext = {
          ...this.sourceCodeContext,
          current_code: this.extractedCode
        }
      }
    },

    // 复制代码
    copyExtractedCode() {
      if (!this.extractedCode) {
        this.$message.warning('暂无代码可复制')
        return
      }

      const textarea = document.createElement('textarea')
      textarea.value = this.extractedCode
      document.body.appendChild(textarea)
      textarea.select()
      document.execCommand('copy')
      document.body.removeChild(textarea)
      this.$message.success('代码已复制到剪贴板')
    },

    // 保存代码到文件
    async saveExtractedCode() {
      if (!this.extractedCode) {
        this.$message.warning('暂无代码可保存')
        return
      }

      this.savingCode = true
      try {
        const response = await request({
          url: `/static_web/api/ai/save_code/${this.currentPageId}/`,
          method: 'post',
          data: {
            source_code: this.extractedCode
          }
        })

        if (response.success) {
          this.$message.success('源代码已保存到文件')
          this.getList()
        }
      } catch (error) {
        this.$message.error('保存失败: ' + error.message)
      } finally {
        this.savingCode = false
      }
    },
    // AI批量创建
    handleAIBatch() {
      if (!this.currentWebsiteId) {
        this.$message.error('请先选择网站')
        return
      }
      // 设置上下文数据
      this.batchContext = {
        website_id: this.currentWebsiteId
      }
      // 清空之前的数据
      this.parsedPages = []
      this.aiBatchVisible = true

      // 清空对话历史，显示建议问题
      this.$nextTick(() => {
        if (this.$refs.batchPageGenerator) {
          this.$refs.batchPageGenerator.clearMessages()
        }
      })
    },
    // 处理AI消息完成事件
    handleAIMessage(message) {
      if (!message || !message.content) return

      // 查找<start--...--end>标记
      const match = message.content.match(/<start--([\s\S]*?)--end>/i)
      if (match) {
        try {
          const jsonStr = match[1].trim()
          const data = JSON.parse(jsonStr)
          if (data.pages && Array.isArray(data.pages)) {
            this.parsedPages = data.pages
            console.log('解析到页面数据:', this.parsedPages)
            this.$message.success(`成功解析 ${data.pages.length} 个页面配置`)
          }
        } catch (e) {
          console.error('解析页面JSON失败:', e)
          this.$message.error('解析页面配置失败，请检查数据格式')
        }
      }
    },
    // 确认批量创建
    async confirmBatchCreate() {
      if (this.parsedPages.length === 0) {
        this.$message.warning('没有可创建的页面')
        return
      }

      this.batchCreating = true
      try {
        const response = await request({
          url: '/static_web/api/page/batch-create/',
          method: 'post',
          data: {
            website_id: this.currentWebsiteId,
            pages: this.parsedPages
          }
        })

        if (response.success) {
          const { created_count, failed_count, errors } = response.data
          let message = `成功创建 ${created_count} 个页面`
          if (failed_count > 0) {
            message += `，${failed_count} 个失败`
            console.error('创建失败的页面:', errors)
          }
          this.$message.success(message)

          // 关闭Drawer并刷新列表
          this.aiBatchVisible = false
          this.getList()

          // 如果有失败的页面，显示详细信息
          if (failed_count > 0) {
            const errorList = errors.map(e => `${e.index}. ${e.title}: ${e.error}`).join('\n')
            this.$alert(errorList, '部分页面创建失败', {
              confirmButtonText: '确定',
              type: 'warning'
            })
          }
        } else {
          this.$message.error(response.msg || '批量创建失败')
        }
      } catch (error) {
        console.error('批量创建错误:', error)
        this.$message.error('批量创建失败: ' + (error.message || '未知错误'))
      } finally {
        this.batchCreating = false
      }
    },
    // 关闭Drawer前的确认
    handleBatchDrawerClose(done) {
      if (this.parsedPages.length > 0) {
        this.$confirm('已收集到页面信息，确定要关闭吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          done()
        }).catch(() => {})
      } else {
        done()
      }
    },
    // 获取页面类型标签
    getPageTypeLabel(type) {
      const types = {
        'landing': '落地页',
        'info_aggregation': '信息聚合页',
        'product': '产品页面',
        'product_catalog': '产品目录页',
        'catalog_landing': '目录落地页',
        'blog_article': '博客文章页'
      }
      return types[type] || type
    },
    // 获取语言标签
    getLanguageLabel(lang) {
      const languages = {
        'en': 'English',
        'zh-cn': '简体中文',
        'es': 'Español',
        'fr': 'Français',
        'de': 'Deutsch',
        'ja': '日本語',
        'ko': '한국어'
      }
      return languages[lang] || lang
    },
    // AI任务成功回调
    handleAISuccess() {
      this.$message.success('AI操作完成')
      this.getList()
    },
    // 内容来源变更处理
    handleContentSourceChange(value) {
      if (value === 'post') {
        // 切换到博客文章时，设置默认部署方式
        if (!this.temp.deployment_method) {
          this.temp.deployment_method = 'replace'
        }
        // 加载文章列表和模板列表
        this.searchPosts('')
        this.loadTemplates()
      } else {
        // 切换到其他类型时，清空博客相关字段
        this.temp.related_post = null
        this.temp.deployment_method = null
        this.temp.template_id = null
      }
    },
    // 加载模板列表
    loadTemplates() {
      if (!this.currentWebsiteId) {
        return
      }
      import('@/api/static_web_template').then(module => {
        const { Get } = module
        const params = `website_id=${this.currentWebsiteId}&is_active=true`
        Get(null, params).then(response => {
          if (response.success && response.data) {
            this.templateList = response.data.data || []
          } else {
            this.templateList = []
          }
        }).catch(error => {
          console.error('加载模板列表失败:', error)
          this.templateList = []
        })
      }).catch(error => {
        console.error('加载模板API模块失败:', error)
        this.templateList = []
      })
    },
    // 搜索博客文章
    searchPosts(query) {
      this.postLoading = true
      // 调用 CMS 的 Post API
      import('@/api/cms/post').then(module => {
        const { Get } = module
        // 构建查询参数
        const params = `page=1&pagesize=50&kw=${query || ''}&status=published`
        Get(null, params).then(response => {
          if (response.success && response.data) {
            this.postList = response.data.data || []
          } else {
            this.postList = []
          }
          this.postLoading = false
        }).catch(error => {
          console.error('加载文章列表失败:', error)
          this.postList = []
          this.postLoading = false
        })
      }).catch(error => {
        console.error('加载API模块失败:', error)
        this.postList = []
        this.postLoading = false
      })
    },
    // 检查是否可以同步到生产环境
    async checkSyncAvailable() {
      try {
        const response = await request({
          url: '/static_web/api/sync/check/',
          method: 'get'
        })
        if (response.success) {
          this.canSyncToProduction = response.data.can_sync
        }
      } catch (error) {
        console.error('检查同步功能失败:', error)
        this.canSyncToProduction = false
      }
    },
    // 同步页面状态到生产环境
    async handleSyncStatusToProduction(row) {
      try {
        // 设置同步状态
        this.$set(row, 'syncing', true)

        const response = await request({
          url: '/static_web/api/sync/page-status-to-production/',
          method: 'post',
          data: {
            page_id: row.id,
            target_project_id: this.productionProjectId
          }
        })

        if (response.success) {
          this.$message.success(response.msg)
        } else {
          this.$message.error(response.msg || '同步失败')
        }
      } catch (error) {
        const errorMsg = error.response?.data?.msg || error.message
        this.$message.error('同步失败: ' + errorMsg)
      } finally {
        this.$set(row, 'syncing', false)
      }
    },
    showEditOperationNoteDialog(row) {
      this.currentEditingPage = row
      this.currentOperationNote = row.operation_note || ''
      this.operationNoteDialogVisible = true
    },
    async savePageOperationNote() {
      if (!this.currentEditingPage) {
        return
      }

      this.savingNote = true
      try {
        const response = await request({
          url: `/static_web/api/page/${this.currentEditingPage.id}/update_operation_note/`,
          method: 'post',
          data: { operation_note: this.currentOperationNote }
        })

        if (response.success) {
          this.$message.success('操作备注保存成功')
          // 更新列表中的显示 - 使用$set确保响应式更新
          this.$set(this.currentEditingPage, 'operation_note', this.currentOperationNote)
          this.operationNoteDialogVisible = false
        } else {
          this.$message.error(response.msg || '保存失败')
        }
      } catch (error) {
        console.error('保存操作备注失败:', error)
        this.$message.error('保存失败')
      } finally {
        this.savingNote = false
      }
    },
    // Git 相关方法
    async loadGitStatus() {
      if (!this.currentWebsiteDomain) {
        return
      }

      this.gitStatusLoading = true
      try {
        const response = await request({
          url: `/static_web/api/site-dirs/${this.currentWebsiteDomain}/status/`,
          method: 'get'
        })

        if (response.success && response.data) {
          this.gitStatus = {
            is_git_repo: response.data.is_git_repo || false,
            has_changes: response.data.has_changes || false,
            needs_pull: response.data.needs_pull || false,
            behind_count: response.data.behind_count || 0,
            ahead_count: response.data.ahead_count || 0,
            current_branch: response.data.current_branch || '',
            remote_url: response.data.remote_url || '',
            modified_files: response.data.modified_files || [],
            untracked_files: response.data.untracked_files || []
          }
        } else {
          // 不是Git仓库
          this.gitStatus = {
            is_git_repo: false,
            has_changes: false,
            needs_pull: false,
            behind_count: 0,
            ahead_count: 0,
            current_branch: '',
            remote_url: ''
          }
        }
      } catch (error) {
        console.error('加载Git状态失败:', error)
        this.gitStatus = {
          is_git_repo: false,
          has_changes: false,
          needs_pull: false,
          behind_count: 0,
          ahead_count: 0,
          current_branch: '',
          remote_url: ''
        }
      } finally {
        this.gitStatusLoading = false
      }
    },
    handleGitCommand(command) {
      switch (command) {
        case 'refresh':
          this.loadGitStatus()
          // 同时刷新页面列表，以显示后端自动更新的任务状态
          this.getList()
          this.$message.success('状态已刷新')
          break
        case 'commit':
          this.handleGitCommit()
          break
        case 'pull':
          this.handleGitPull()
          break
      }
    },
    async handleGitCommit() {
      if (!this.currentWebsiteDomain) {
        return
      }

      const commitMessage = await this.$prompt('请输入提交信息', '提交并推送', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: 'Update website files',
        inputPlaceholder: '请输入提交信息'
      }).catch(() => null)

      if (!commitMessage || !commitMessage.value) {
        return
      }

      const loading = this.$loading({
        lock: true,
        text: '正在提交并推送...',
        spinner: 'el-icon-loading'
      })

      try {
        const response = await request({
          url: `/static_web/api/site-dirs/${this.currentWebsiteDomain}/commit/`,
          method: 'post',
          data: {
            commit_message: commitMessage.value,
            push: true
          }
        })

        loading.close()

        if (response.success) {
          this.$message.success('提交并推送成功')
          // 刷新Git状态
          await this.loadGitStatus()
        } else {
          this.$message.error(response.msg || '操作失败')
        }
      } catch (error) {
        loading.close()
        console.error('Git提交失败:', error)
        this.$message.error('提交失败: ' + (error.message || '未知错误'))
      }
    },
    async handleGitPull() {
      if (!this.currentWebsiteDomain) {
        return
      }

      this.$confirm('确定要从远程仓库拉取最新代码吗？', '拉取更新', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(async() => {
        const loading = this.$loading({
          lock: true,
          text: '正在拉取更新...',
          spinner: 'el-icon-loading'
        })

        try {
          const response = await request({
            url: `/static_web/api/site-dirs/${this.currentWebsiteDomain}/pull/`,
            method: 'post'
          })

          loading.close()

          if (response.success) {
            this.$message.success('拉取成功')
            // 刷新Git状态和页面列表
            await this.loadGitStatus()
            this.getList()
          } else {
            this.$message.error(response.msg || '拉取失败')
          }
        } catch (error) {
          loading.close()
          console.error('Git拉取失败:', error)
          this.$message.error('拉取失败: ' + (error.message || '未知错误'))
        }
      }).catch(() => {
        // 用户取消
      })
    },
    // 从 Cookie 加载筛选条件
    loadFilterFromCookies() {
      const savedStatus = Cookies.get('static_web_pages_filter_status')
      const savedPageType = Cookies.get('static_web_pages_filter_page_type')
      const savedKeyword = Cookies.get('static_web_pages_filter_kw')
      const savedTasks = Cookies.get('static_web_pages_filter_tasks')
      const savedExcludeTasks = Cookies.get('static_web_pages_filter_exclude_tasks')
      const savedSyncToProduction = Cookies.get('static_web_pages_sync_to_production')

      if (savedStatus) {
        this.listQuery.status = savedStatus
      }
      if (savedPageType) {
        this.listQuery.page_type = savedPageType
      }
      if (savedKeyword) {
        this.listQuery.kw = savedKeyword
      }
      if (savedTasks) {
        try {
          this.listQuery.tasks = JSON.parse(savedTasks)
        } catch (e) {
          this.listQuery.tasks = []
        }
      }
      if (savedExcludeTasks) {
        try {
          this.listQuery.exclude_tasks = JSON.parse(savedExcludeTasks)
        } catch (e) {
          this.listQuery.exclude_tasks = []
        }
      }
      // 加载同步开关状态,默认为true
      if (savedSyncToProduction !== undefined) {
        this.syncToProduction = savedSyncToProduction === 'true'
      }
    },
    // 保存筛选条件到 Cookie
    saveFilterToCookies() {
      // 保存筛选条件到 Cookie（7天有效期）
      Cookies.set('static_web_pages_filter_status', this.listQuery.status || '', { expires: 7 })
      Cookies.set('static_web_pages_filter_page_type', this.listQuery.page_type || '', { expires: 7 })
      Cookies.set('static_web_pages_filter_kw', this.listQuery.kw || '', { expires: 7 })
      Cookies.set('static_web_pages_filter_tasks', JSON.stringify(this.listQuery.tasks || []), { expires: 7 })
      Cookies.set('static_web_pages_filter_exclude_tasks', JSON.stringify(this.listQuery.exclude_tasks || []), { expires: 7 })
    },
    // 同步设置变更处理
    handleSyncSettingChange(value) {
      // 保存同步开关状态到Cookie（30天有效期）
      Cookies.set('static_web_pages_sync_to_production', value.toString(), { expires: 30 })
      if (value) {
        this.$message.success('已开启自动同步到生产环境')
      } else {
        this.$message.info('已关闭自动同步到生产环境')
      }
    },
    // 同步单个字段到生产环境
    syncFieldToProduction(pageId, fieldName, fieldValue, fieldLabel) {
      // 静默同步,不显示loading
      import('@/api/static_web/sync_production').then(module => {
        const { syncPageStatusToProduction } = module
        syncPageStatusToProduction(pageId, this.productionProjectId).then(response => {
          if (response.success) {
            // 静默成功,不提示
            console.log(`${fieldLabel}已同步到生产环境`)
          }
        }).catch(error => {
          // 同步失败时提示,但不影响本地操作
          console.error('同步到生产环境失败:', error)
          this.$message.warning(`${fieldLabel}同步到生产环境失败,请手动同步`)
        })
      })
    },
    // 批量选择处理
    handleSelectionChange(selection) {
      this.multipleSelection = selection
    },
    // 批量同步到生产环境
    async handleBatchSyncToProduction() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请先选择要同步的页面')
        return
      }

      const pageIds = this.multipleSelection.map(page => page.id)
      const pageTitles = this.multipleSelection.map(page => page.title).join('、')

      this.$confirm(
        `确定要将以下 ${this.multipleSelection.length} 个页面的状态同步到生产环境吗？\n\n${pageTitles}`,
        '批量同步确认',
        {
          confirmButtonText: '确定同步',
          cancelButtonText: '取消',
          type: 'warning',
          dangerouslyUseHTMLString: true
        }
      ).then(async() => {
        this.batchSyncing = true
        const loading = this.$loading({
          lock: true,
          text: `正在同步 ${this.multipleSelection.length} 个页面...`,
          spinner: 'el-icon-loading'
        })

        try {
          const response = await request({
            url: '/static_web/api/sync/batch-page-status-to-production/',
            method: 'post',
            data: {
              page_ids: pageIds,
              target_project_id: this.productionProjectId
            }
          })

          loading.close()

          if (response.success) {
            const { success_count, failed_count, results } = response.data

            let message = `成功同步 ${success_count} 个页面`
            if (failed_count > 0) {
              message += `，${failed_count} 个失败`
            }

            this.$notify({
              title: '批量同步完成',
              message: message,
              type: success_count > 0 ? 'success' : 'error',
              duration: 5000
            })

            // 如果有失败的,显示详细信息
            if (failed_count > 0) {
              const failedList = results
                .filter(r => !r.success)
                .map(r => `• ${r.page_title}: ${r.error}`)
                .join('\n')

              this.$alert(failedList, '部分页面同步失败', {
                confirmButtonText: '确定',
                type: 'warning'
              })
            }
          } else {
            this.$message.error(response.msg || '批量同步失败')
          }
        } catch (error) {
          loading.close()
          const errorMsg = error.response?.data?.msg || error.message
          this.$message.error('批量同步失败: ' + errorMsg)
          console.error('批量同步错误:', error)
        } finally {
          this.batchSyncing = false
        }
      }).catch(() => {
        // 用户取消
      })
    }
  }
}
</script>

<style scoped>
.filter-container {
  margin-bottom: 20px;
}
.filter-item {
  margin-right: 10px;
  margin-bottom: 10px;
}

/* 源代码面板样式 */
.source-code-panel {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.panel-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 15px;
  background: #f5f7fa;
  border-bottom: 1px solid #dcdfe6;
}

.panel-title {
  font-weight: 600;
  font-size: 14px;
  color: #303133;
}

.code-stats {
  margin-left: 10px;
  font-size: 12px;
  color: #909399;
  font-weight: normal;
}

.panel-actions {
  display: flex;
  gap: 5px;
}

.code-editor {
  flex: 1;
}

.code-editor ::v-deep textarea {
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 13px;
  line-height: 1.6;
  border: none;
  border-radius: 0;
  padding: 15px;
}

/* 批量创建Drawer样式 */
.batch-drawer-content {
  height: calc(100vh - 60px);
  display: flex;
  flex-direction: column;
  padding: 20px;
}

.batch-drawer-content .el-row {
  flex: 1;
  overflow: hidden;
}

.batch-drawer-content .el-col {
  height: 100%;
  display: flex;
  flex-direction: column;
}

/* AIInnerChat 在 Drawer 中的样式 */
.batch-drawer-content .ai-inner-chat {
  height: 100%;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  overflow: hidden;
}

/* Drawer底部按钮 */
.drawer-footer {
  padding: 15px 0 0;
  border-top: 1px solid #e4e7ed;
  text-align: right;
  margin-top: 20px;
}

/* 批量预览面板样式 */
.batch-preview-panel {
  display: flex;
  flex-direction: column;
  height: 100%;
  background: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  overflow: hidden;
}

.batch-preview-panel .panel-header {
  background: #fff;
  border-bottom: 1px solid #dcdfe6;
}

.page-count {
  margin-left: 8px;
  color: #1EB7E6;
  font-weight: bold;
}

.pages-preview-list {
  flex: 1;
  overflow-y: auto;
  padding: 15px;
}

.page-preview-item {
  margin-bottom: 12px;
}

.page-preview-item:last-child {
  margin-bottom: 0;
}

.page-item-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.page-number {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  background: #1EB7E6;
  color: white;
  border-radius: 50%;
  font-size: 12px;
  font-weight: bold;
  margin-right: 10px;
  flex-shrink: 0;
}

.page-item-header h4 {
  margin: 0;
  font-size: 15px;
  font-weight: 600;
  color: #303133;
  flex: 1;
}

.page-item-details {
  font-size: 13px;
  color: #606266;
  line-height: 1.8;
}

.page-item-details p {
  margin: 5px 0;
}

.page-item-details strong {
  font-weight: 600;
  color: #303133;
  margin-right: 5px;
}

.page-desc {
  color: #909399;
  font-style: italic;
  margin-top: 8px !important;
}

.empty-preview {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #909399;
}

.empty-preview p {
  margin-top: 15px;
  font-size: 14px;
}
</style>
